import os
import re

# 指定需要扫描的目录
directory = 'E:\\crp_box_e\\src'

# 指定要处理的文件扩展名
extensions = ['.h', '.cpp']

# 替换规则1
# replace_rule1 = r"Tr\(\)->translate\((TR_[a-zA-Z0-9_]+)\)"
# replace_rule1 = r"registerMainMenuFunc\((TR_[a-zA-Z0-9_]+)"
replace_rule1 = r'"(TR_[a-zA-Z0-9_]+)"'
# 替换规则2
# replace_rule2 = r"unregisterMainMenuFunc\((TR_[a-zA-Z0-9_]+)\)"
# replace_rule2 = r'str\("(TR_[a-zA-Z0-9_]+)"\)'

                     
def replace_in_file(file_path):
    # 打开文件用于读取和更新（原地修改），并指定编码为UTF-8
    with open(file_path, 'r+', encoding='utf-8') as file:
        content = file.read()

        # 处理每一行内容，这里假设文件不是特别大以至于不能一次性加载到内存中
        lines = content.splitlines(True)  # 保留换行符
        for i, line in enumerate(lines):
            # 处理第一个替换规则
            # line1 = re.sub(replace_rule1, r'Tr()->translate("\1")', line)
            # 处理第二个替换规则
            # replaced_line = re.sub(replace_rule2, r'qtr("\1")', line1)
            # 处理第一个替换规则
            # line1 = re.sub(replace_rule1, r'registerMainMenuFunc("\1"', line)
            # 处理第二个替换规则
            replaced_line = re.sub(replace_rule1, r'\1', line)
            # replaced_line = re.sub(replace_rule2, r'str("\1"', line1)
            # 更新行内容
            lines[i] = replaced_line

        # 将处理后的内容写回文件，由于之前已经指定了UTF-8编码，所以写入时也会是UTF-8格式
        file.seek(0)  # 移动到文件开头
        file.truncate()  # 清空原有内容
        file.writelines(lines)  # 写入新内容


for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith(tuple(extensions)):
            file_path = os.path.join(root, file)
            replace_in_file(file_path)

print("Finished processing files.")
